<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getUserInfo } from '@/api/user'

const router = useRouter()
interface UserInfo {
  id: number
  phone: string
  userName: string
  email: string
}

const userInfo = ref<UserInfo | null>(null)
const loading = ref(false)

// 获取用户信息
const handleGetUserInfo = async () => {
  try {
    loading.value = true
    const { data } = await getUserInfo()
    userInfo.value = data
    ElMessage.success('获取用户信息成功')
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '获取用户信息失败')
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      router.push('/login')
    }
  } finally {
    loading.value = false
  }
}

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('token')
  router.push('/login')
  ElMessage.success('退出成功')
}
</script>

<template>
  <div class="home-container">
    <div class="home-box">
      <h2>首页</h2>
      <div class="button-group">
        <el-button
          type="primary"
          :loading="loading"
          @click="handleGetUserInfo"
        >
          获取用户信息
        </el-button>
        <el-button
          type="danger"
          @click="handleLogout"
        >
          退出登录
        </el-button>
      </div>

      <div v-if="userInfo" class="user-info">
        <h3>用户信息</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="用户ID">{{ userInfo.id }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ userInfo.phone }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ userInfo.userName }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ userInfo.email }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </div>
  </div>
</template>

<style scoped>
.home-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--el-bg-color-page);
}

.home-box {
  width: 600px;
  padding: 40px;
  background-color: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
}

.home-box h2 {
  text-align: center;
  color: var(--el-color-primary);
  margin-bottom: 30px;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 30px;
}

.user-info {
  margin-top: 20px;
}

.user-info h3 {
  color: var(--el-color-primary);
  margin-bottom: 20px;
}

:deep(.el-button--primary:not(:disabled)) {
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
}

:deep(.el-button--primary:not(:disabled):hover) {
  background-color: var(--el-color-primary-light-3);
  border-color: var(--el-color-primary-light-3);
}

:deep(.el-descriptions) {
  margin-top: 20px;
}

:deep(.el-descriptions__label) {
  width: 100px;
  justify-content: center;
  background-color: var(--el-fill-color-light);
}
</style>
